<?php

namespace App\Jobs;

use App\Models\Goods;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\OrderInfo;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;
use Yansongda\Supports\Log;

class AutoClearOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $order_id;
    protected $order_sn;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($order_id,$order_sn)
    {
        $this->order_id = $order_id;
        $this->order_sn = $order_sn;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \DB::beginTransaction();

        try {
            $order = Order::query()->where(['id'=>$this->order_id,'order_sn'=>$this->order_sn])->first();

            if($order->status == 1){
                $this->delete();
                return;
            }
            //减库存
            $order_info = OrderInfo::query()->where([
                'order_id'=>$this->order_id,
                'order_sn'=>$this->order_sn,
            ])->get()->toArray();

            foreach ($order_info as $k => $v) {
                $goods_sku = GoodsSku::query()->where([
                    'goods_id'=>$v['goods_id'],
                    'sku_list'=>$v['sku_list']
                ])->lockForUpdate()->first();

                $goods_sku->increment('inventory',$v['number']);

                $goods = Goods::query()->where(['id'=>$v['goods_id']])->lockForUpdate()->first();
                $goods->increment('inventory',$v['number']);

                //如果商品的秒杀状态是1 那么还要减秒杀hash表的内容
                if($goods->kill_status == 1){
                    $seckill = $goods->seckill_goods()->where(['kill_status'=>1])->first();
                    $key = 'goods_sku_stock:goods_id:'.$v['goods_id'].':active_id:'.$seckill->id;

                    $old_inventory = Redis::hget($key,$v['sku_list']);
                    $new_inventory = $old_inventory + $v['number'];
                    Redis::hset($key,$v['sku_list'],$new_inventory);

                    $expired_time = strtotime($seckill['end_time']) - time();
                    //设置key的过期时间
                    Redis::expire($key, $expired_time);
                }
            }

            Order::query()->where(['id'=>$this->order_id,'order_sn'=>$this->order_sn])->delete();

            OrderInfo::query()->where([
                'order_id'=>$this->order_id,
                'order_sn'=>$this->order_sn,
            ])->delete();

            \DB::commit();
        }catch (\Exception $exception){
            Log::info('普通订单自动清理失败_'.$this->order_sn.'---' . $exception->getMessage());
        }

    }
}
